#include "udp_client.h"
#include <QDebug>
TzUdpClient::TzUdpClient(QObject *parent) : QObject(parent)
{
    m_parseThread = new ParseThread(this);
    m_parseThread->start();
    m_Client = new QUdpSocket(this);
    m_Client->bind(QHostAddress("127.0.0.1"),3333);
    auto status = m_Client->open(QIODevice::ReadWrite);
    connect(m_Client,&QUdpSocket::readyRead,this,&TzUdpClient::readyData);

    connect(m_parseThread,&ParseThread::signRecvPhotoInfo,[=]{
        sendData(QString("1").toLocal8Bit().data(),2);
    });
}

void TzUdpClient::readyData()
{
    QByteArray datagram;
    while (m_Client->hasPendingDatagrams()) {
        datagram.clear();
        auto currentSize = m_Client->pendingDatagramSize();
        datagram.resize(currentSize);
        m_dataSize += currentSize;
        auto size = m_Client->readDatagram(datagram.data(),datagram.size());
        m_dataCache.append(datagram);
    }
    m_dataCache.resize(m_dataSize);
    m_dataSize = 0;
    if(m_dataCache.size() > 16){
        m_parseThread->recvData(m_dataCache);
        m_dataCache.clear();
    }else{
        qDebug()<<"Continue to send";
        return;
    }
}

void TzUdpClient::sendData(char* data, int size)
{
    for (int i = 0 ; i < 100 ;i ++) {
        m_Client->writeDatagram(data,size,
                                QHostAddress("127.0.0.1"),//QHostAddress::Broadcast,    //udp广播地址
                                4444);
        m_Client->waitForBytesWritten();
        m_Client->waitForReadyRead(1);
    }
}

void TzUdpClient::slotRecvPhotoInfoBackResponsePackage(QImage image)
{
    signRecvPhotoInfoBackResponsePackage(image);
}
